package com.ruoyi.collect.service.impl;

import com.ruoyi.basic.domain.Country;
import com.ruoyi.basic.domain.Language;
import com.ruoyi.basic.mapper.CountryMapper;
import com.ruoyi.basic.mapper.LanguageMapper;
import com.ruoyi.collect.service.IDataDictionaryService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.movie.domain.Actor;
import com.ruoyi.movie.domain.MovieBasics;
import com.ruoyi.movie.mapper.ActorMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据字典服务实现
 * 自动维护采集过程中的基础数据（国家、演员、语言等）
 *
 * @author ruoyi
 * @date 2025-11-13
 */
@Service
public class DataDictionaryServiceImpl implements IDataDictionaryService {

    private static final Logger log = LoggerFactory.getLogger(DataDictionaryServiceImpl.class);

    @Autowired
    private CountryMapper countryMapper;

    @Autowired
    private ActorMapper actorMapper;

    @Autowired
    private LanguageMapper languageMapper;

    /**
     * 从影视信息中提取并保存基础数据字典
     */
    @Override
    @Transactional
    public void extractAndSaveDictionaries(MovieBasics movie) {
        if (movie == null) {
            return;
        }

        try {
            // 保存国家/地区
            if (StringUtils.isNotEmpty(movie.getArea())) {
                saveCountries(movie.getArea());
            }

            // 保存演员
            if (StringUtils.isNotEmpty(movie.getActorText())) {
                saveActors(movie.getActorText());
            }

            // 保存导演
            if (StringUtils.isNotEmpty(movie.getDirectorText())) {
                saveDirectors(movie.getDirectorText());
            }

            // 保存编剧
            if (StringUtils.isNotEmpty(movie.getWriterText())) {
                saveWriters(movie.getWriterText());
            }

            // 保存语言
            if (StringUtils.isNotEmpty(movie.getLanguages())) {
                saveLanguages(movie.getLanguages());
            }

            log.debug("数据字典提取完成: {}", movie.getTitle());
        } catch (Exception e) {
            log.error("提取数据字典失败: {}", movie.getTitle(), e);
            // 不影响主流程，吞掉异常
        }
    }

    /**
     * 保存国家信息（去重）
     */
    @Override
    public void saveCountries(String areaText) {
        if (StringUtils.isEmpty(areaText)) {
            return;
        }

        List<String> countries = parseText(areaText);
        int inserted = 0;

        for (String countryName : countries) {
            try {
                // 检查是否已存在
                Country query = new Country();
                query.setName(countryName);
                List<Country> existing = countryMapper.selectCountryList(query);

                if (existing == null || existing.isEmpty()) {
                    // 不存在，插入新记录
                    Country country = new Country();
                    country.setName(countryName);
                    country.setType("0"); // 默认类型
                    country.setCreateTime(DateUtils.getNowDate());
                    countryMapper.insertCountry(country);
                    inserted++;
                    log.debug("新增国家: {}", countryName);
                }
            } catch (Exception e) {
                log.warn("保存国家失败: {}", countryName, e);
            }
        }

        if (inserted > 0) {
            log.info("新增 {} 个国家/地区", inserted);
        }
    }

    /**
     * 保存演员信息（去重）
     */
    @Override
    public void saveActors(String actorText) {
        savePersons(actorText, "演员");
    }

    /**
     * 保存导演信息（去重）
     */
    @Override
    public void saveDirectors(String directorText) {
        savePersons(directorText, "导演");
    }

    /**
     * 保存编剧信息（去重）
     */
    @Override
    public void saveWriters(String writerText) {
        savePersons(writerText, "编剧");
    }

    /**
     * 保存人物信息（演员/导演/编剧）到actor表
     */
    private void savePersons(String personText, String type) {
        if (StringUtils.isEmpty(personText)) {
            return;
        }

        List<String> persons = parseText(personText);
        int inserted = 0;

        for (String personName : persons) {
            try {
                // 检查是否已存在
                Actor query = new Actor();
                query.setName(personName);
                List<Actor> existing = actorMapper.selectActorList(query);

                if (existing == null || existing.isEmpty()) {
                    // 不存在，插入新记录
                    Actor actor = new Actor();
                    actor.setName(personName);
                    actor.setGender("3"); // 未知性别
                    actor.setCreateTime(DateUtils.getNowDate());
                    actorMapper.insertActor(actor);
                    inserted++;
                    log.debug("新增{}: {}", type, personName);
                }
            } catch (Exception e) {
                log.warn("保存{}失败: {}", type, personName, e);
            }
        }

        if (inserted > 0) {
            log.info("新增 {} 个{}", inserted, type);
        }
    }

    /**
     * 保存语言信息（去重）
     */
    @Override
    public void saveLanguages(String languageText) {
        if (StringUtils.isEmpty(languageText)) {
            return;
        }

        List<String> languages = parseText(languageText);
        int inserted = 0;

        for (String languageName : languages) {
            try {
                // 检查是否已存在
                Language query = new Language();
                query.setName(languageName);
                List<Language> existing = languageMapper.selectLanguageList(query);

                if (existing == null || existing.isEmpty()) {
                    // 不存在，插入新记录
                    Language language = new Language();
                    language.setName(languageName);
                    language.setCreateTime(DateUtils.getNowDate());
                    languageMapper.insertLanguage(language);
                    inserted++;
                    log.debug("新增语言: {}", languageName);
                }
            } catch (Exception e) {
                log.warn("保存语言失败: {}", languageName, e);
            }
        }

        if (inserted > 0) {
            log.info("新增 {} 个语言", inserted);
        }
    }

    /**
     * 解析逗号分隔的文本
     */
    private List<String> parseText(String text) {
        if (StringUtils.isEmpty(text)) {
            return new ArrayList<>();
        }

        return Arrays.stream(text.split("[,，]")) // 支持中英文逗号
                .map(String::trim)
                .filter(StringUtils::isNotEmpty)
                .distinct() // 去重
                .collect(Collectors.toList());
    }

    // ========== 批量保存方法（性能优化） ==========

    /**
     * 批量保存国家（使用INSERT IGNORE避免重复）
     */
    @Override
    public void batchSaveCountries(List<String> countries) {
        if (countries == null || countries.isEmpty()) {
            return;
        }

        try {
            List<Country> countryList = new ArrayList<>();
            for (String name : countries) {
                Country country = new Country();
                country.setName(name);
                country.setType("0");
                country.setCreateTime(DateUtils.getNowDate());
                countryList.add(country);
            }

            int inserted = countryMapper.batchInsertCountryIgnore(countryList);
            if (inserted > 0) {
                log.info("批量新增 {} 个国家/地区（去重后）", inserted);
            }
        } catch (Exception e) {
            log.error("批量保存国家失败", e);
        }
    }

    /**
     * 批量保存演员（使用INSERT IGNORE避免重复）
     */
    @Override
    public void batchSaveActors(List<String> actors) {
        batchSavePersons(actors, "演员");
    }

    /**
     * 批量保存导演（使用INSERT IGNORE避免重复）
     */
    @Override
    public void batchSaveDirectors(List<String> directors) {
        batchSavePersons(directors, "导演");
    }

    /**
     * 批量保存编剧（使用INSERT IGNORE避免重复）
     */
    @Override
    public void batchSaveWriters(List<String> writers) {
        batchSavePersons(writers, "编剧");
    }

    /**
     * 批量保存人物（演员/导演/编剧）
     */
    private void batchSavePersons(List<String> persons, String type) {
        if (persons == null || persons.isEmpty()) {
            return;
        }

        try {
            List<Actor> actorList = new ArrayList<>();
            for (String name : persons) {
                Actor actor = new Actor();
                actor.setName(name);
                actor.setGender("3"); // 未知性别
                actor.setCreateTime(DateUtils.getNowDate());
                actorList.add(actor);
            }

            int inserted = actorMapper.batchInsertActorIgnore(actorList);
            if (inserted > 0) {
                log.info("批量新增 {} 个{}（去重后）", inserted, type);
            }
        } catch (Exception e) {
            log.error("批量保存{}失败", type, e);
        }
    }

    /**
     * 批量保存语言（使用INSERT IGNORE避免重复）
     */
    @Override
    public void batchSaveLanguages(List<String> languages) {
        if (languages == null || languages.isEmpty()) {
            return;
        }

        try {
            List<Language> languageList = new ArrayList<>();
            for (String name : languages) {
                Language language = new Language();
                language.setName(name);
                language.setCreateTime(DateUtils.getNowDate());
                languageList.add(language);
            }

            int inserted = languageMapper.batchInsertLanguageIgnore(languageList);
            if (inserted > 0) {
                log.info("批量新增 {} 个语言（去重后）", inserted);
            }
        } catch (Exception e) {
            log.error("批量保存语言失败", e);
        }
    }
}
